<#import "/spring.ftl" as spring />
<#import "html-macro.ftl" as h />
<#import "declaration-macro.ftl" as d />
<div class="row">
    <div class="column">
        <button id="returnBtn" class="tiny ui labeled icon button blue">
            <i class="small fa-arrow-left icon"></i>
            返回
        </button>
        <button id="newBtn" class="tiny ui labeled icon button blue">
            <i class="plus icon"></i>
            新增
        </button>
        <button id="saveBtn" class="tiny ui labeled icon button blue">
            <i class="save icon"></i>
            暂存
        </button>
    <#if !d.isInsertPage__>
        <button id="copyBtn" class="tiny ui labeled icon button blue">
            <i class="copy icon"></i>
            复制
        </button>
    </#if>
    <#--<button class="tiny ui labeled icon button blue">-->
    <#--<i class="print icon"></i>-->
    <#--打印-->
    <#--</button>-->
        <button id="submitBtn" class="tiny ui labeled icon button blue allSubmit ">
            <i class="small fa-check icon"></i>
            提交
        </button>
        <button id="useTemplateBtn" class="tiny ui labeled icon button blue">
            <i class="small add circle icon"></i>
            使用模板
        </button>
        <button id="prepareSveAsModel" class="tiny ui labeled icon button blue">
            <i class="small add circle icon"></i>
            另存为模板
        </button>
        <button id="uploadDeclarationAttachmentBtn" class="tiny ui labeled icon button blue">
            <i class="small upload icon"></i>
            报关资料上传
        </button>
    <#if d.declarationType__>
        <button class="tiny ui labeled icon button blue" id="good_importButton">
            <i class="small add circle icon"></i>
            报关单excel导入
        </button>
        <a href="<@spring.url "/order/download/excel_export_declaration"/>">下载模板</a>
        <input type="file" id="hgImportFile" name="file" accept=".xls" style="display:none;"/>

        <div style="display:none;" id="fileDiv">
            <form id="fileForm" method="post"
                  action="/business/importExcel?isTongguanYth=${declaration.isTongguanYth }&tradeType=${declaration.tradeType}"
                  enctype="multipart/form-data" style="padding-top:20px;padding-left:5px">
                <input type="file" id="excelImportFile" name="excelImportFile" accept=".xls"/>
            </form>
        </div>
    </#if>
    </div>
</div>

<script>
    $(function () {
        if ($.fn.order.isExport) {
            $(good_importButton).click(function (event) {

                layer.open({
                    type: 1,
                    title: 'excel导入',
                    shadeClose: false, //点击遮罩关闭层
                    area: ['400px', '300px'],
                    content: $("#fileDiv"),
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        layero.find('#fileForm').submit();
                    },
                });
            });
        }

        $(importContainerListButton).click(function (event) {
            $.getScript("/excel/jszip.js", function () {
                $.getScript("/excel/xlsx.js", function () {
                    importContainerList(event);
                });
            });
        });
        $(importContainerListButton).unbind("click").bind("click", function () {
            importContainerList(event);
        })
        $(fileForBox).change(function (event) {
            $.getScript("/excel/jszip.js", function () {
                $.getScript("/excel/xlsx.js", function () {
                    importContainerList(event);
                });
            });
        });
    });
    var X = XLSX;
    var importContainerListSpeed = 100;//柜号数据导入速度，其实是导入每行柜号前需等待的毫秒数
    function importContainerList(event) {
        var importContainerLayerIndex;
        var target = event.target;
        if (target.tagName == 'I') {
            target = target.parentElement;
        } else {
            target = event.target;
        }
        /*var ov = target.textContent;*/
        var ov = $(target).html();
        target.disabled = true;
        try {
            target.textContent = "Loading...";
            importContainerLayerIndex = layer.load(1, {
                shade: [0.5, '#000'] //0.1透明度的白色背景
            });
        } catch (e) {
        }
        var onComplete = function () {
            target.disabled = false;
            try {
                /*target.textContent = ov;*/
                $(target).html(ov);
                layer.close(importContainerLayerIndex);

            } catch (e) {
            }
        }
        var importDataRow = function (rows, posi) {
            if (posi >= rows.length) {
                onComplete.apply();
                if (posi == 0) {
                    alert("识别到柜号数据[0]行。");
                }
            }
            $.each(rows, function (i, n) {
                var $containersAdd = $(
                        "#containersAdd");
                if (!$containersAdd.is(":hidden")) {
                    $containersAdd.click();
                }
                $("#containerNo").val(n.集装箱号);
                $("#containerWeight").val(n['自重'] == undefined ? '' : n['自重']);
                var $ctSizeDropdown = $(
                        "#containerStandard").parent();
                var ctSize;
                if (n.集装箱规格 == "20") {
                    ctSize = "S";
                } else if (n.集装箱规格 == "40") {
                    ctSize = "L";
                } else {
                    /*layer.alert("集装箱号" + n.集装箱号 +
                                "的集装箱规格录入错误，请修改后重新导入数据"
                    );*/
                    var containerImportLayer = layer.confirm("集装箱号" + n.集装箱号 +
                            "的集装箱规格录入错误，请修改后重新导入数据,是否要系统帮你删除已经导入的柜号数据",
                            {
                                btn: ['是', '否'] //按钮
                            }, function () {
                                $("#containersCheckAll").click();
                                $("#containersBatch").click();
                                $("#containerNo").val("");
                                $("#containerWeight").val("");
                                $("#containersCancle").click();
                                layer.close(containerImportLayer);
                            }, function () {
                                layer.close(containerImportLayer);
                            });
                    return false;
                }
                /*var ctSize = n.集装箱规格 == "20" ? "S"
                        : "L";*/
                $ctSizeDropdown.dropdown(
                        "set selected",
                        ctSize);
                $("#containersSave").click();
            });
            onComplete.apply();
        }
        var importDataRow_old = function (rows, posi) {
            var autoConfirmMsg = function () {
                if ($(".messager-window").length > 0) {
                    $(".l-btn-text").click();
                }
            }
            try {
                jzxggselect_123_show.focus();
            } catch (e) {
            }
            try {
                if (posi >= rows.length) {
                    onComplete.apply();
                    if (posi == 0) {
                        alert("识别到柜号数据[0]行。");
                    }
                }
                else {
                    box_jzxh.value = rows[posi]['集装箱号'];
                    autoConfirmMsg.apply();
                    var dtype = rows[posi]['集装箱规格'] == "20" ? "S" : "L";
                    $(".datagrid-row")["S" == dtype ? 0 : 1].click();
                    autoConfirmMsg.apply();
                    box_jzxzz.value = rows[posi]['自重'] == undefined ? "" : rows[posi]['自重'];
                    autoConfirmMsg.apply();
                    box_addButton.click()
                    autoConfirmMsg.apply();
                    setTimeout(function () {
                        importDataRow.call(importDataRow, rows, posi + 1);
                    }, importContainerListSpeed);
                }
            } catch (e) {
                alert("导入失败。" + e);
                onComplete.apply();
            }
        }
        var files = fileForBox.files;
        if (target.type != 'file' || files.length <= 0) {
            fileForBox.click();
            onComplete.apply();
            return;
        }
        var f = files[0];
        var reader = new FileReader();
        var name = f.name;
        reader.onloadstart = function (e) {
            console.log(e.target.result);
        };
        reader.onload = function (e) {
            try {
                var data = e.target.result;
                var wb;
                wb = X.read(data, {type: 'binary'});
                var jarray = X.utils.sheet_to_row_object_array(wb.Sheets[wb.SheetNames[0]]);
                importDataRow(jarray, 0);
//onComplete.apply();
            } catch (ex) {
                alert("导入失败。" + ex);
                onComplete.apply();
            }
            $("#fileForBox").val("");
        };
        try {
            reader.readAsBinaryString(f);
        } catch (ex) {
            alert("导入失败。" + ex);
            onComplete.apply();
        }
    }

</script>

<script
        type="text/javascript">
    /**
     *自定义检验规则
     */
    $.fn.form.settings.rules.customRules_1 = function (value, key) {
        if ($(key).parents("#goodsTable")
                && $(key).parents("#goodsTable").find("tbody tr").length) {
            return ($(key).text() == value);
        } else {
            return true;
        }
    };
    /**
     *自定义最大字节检验规则
     */
    $.fn.form.settings.rules.maxBytes=function(value,key){
        var totalBytes=function(str){
            var count=0;
            var reg=/[\u4e00-\u9fa5]/;
            for(var i=0;i<str.length;i++){
                if(reg.test(str[i])){
                    count+=2;
                }else{
                    count+=1;
                }
            }
            return count;
        }
        return totalBytes(value)<=parseInt(key)?true:false;
    };


    /**
     * 说明从什么页面进入此页面，目前只在客户驳回列表中使用
     */
    var validationRules = {
        declarationFormRule: {
            fields: {
                companyco: {
                    identifier: 'company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '收发货人为必填项'
                        },
                        {
                            type: 'maxLength[10]',
                            prompt: '收发货人公司申报代码最大长度10'
                        }
                    ]
                },
                /*company_name: {
                    identifier: 'company_name',
                    rules: [
                        {
                            type: 'maxLength[10]',
                            prompt: '收发货人公司名称最大长度10'
                        }
                    ]
                },*/
                fahuo_company_co: {
                    identifier: 'fahuo_company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '消费使用单位为必填项'
                        },
                        {
                            type: 'maxLength[10]',
                            prompt: '消费使用单位申报代码/生产销售单位申报代码最大长度10'
                        }
                    ]
                },
                shenbao_company_co: {
                    identifier: 'shenbao_company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '申报单位为必填项'
                        }
                    ]
                },
                /*tex_company: {
                identifier: 'tex_company',
                rules: [
                {
                type: 'empty'
                }
                ]
                },*/
                trade_mode_code: {
                    identifier: 'trade_mode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '监管方式为必填项'
                        }
                    ]
                },
                levymode_code: {
                    identifier: 'levymode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '征免性质为必填项'
                        }
                    ]
                },
                arrived_country_code: {
                    identifier: 'arrived_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '运抵国为必填项'
                        }
                    ]
                },
                trading_country_code: {
                    identifier: 'trading_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '贸易国为必填项'
                        }
                    ]
                },
                arrived_port_code: {
                    identifier: 'arrived_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '指运港为必填项'
                        }
                    ]
                },
                goods_addr_code: {
                    identifier: 'goods_addr_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '境内目的地/境内货源地不能为空'
                        }
                    ]
                },
                goods_count: {
                    identifier: 'goods_count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '件数为必填项'
                        },
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '件数格式错误，允许最大值999999999'
                        }
                    ]
                },
                goods_package_code: {
                    identifier: 'goods_package_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装种类为必填项'
                        }
                    ]
                },
                gross_weight: {
                    identifier: 'gross_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '毛重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重的最大值为999999999'
                        }
                    ]
                },
                net_weight: {
                    identifier: 'net_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '净重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '净重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'lessThan[gross_weight]',
                            prompt: '请输入小于等于毛重'
                        }
                    <#if d.declarationType__>
                        ,
                        {
                            type: 'customRules_1[.total-net-weight]',
                            prompt: '总净重要等于净重总汇'
                        }
                    </#if>
                    ]
                },
                deal_mode_code: {
                    identifier: 'deal_mode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '成交方式为必填项'
                        }
                    ]
                },
                record_id: {
                    identifier: 'record_id',
                    rules: [
                    <#if d.isProcessTrade__>
                        {
                            type: 'empty',
                            prompt: '备案号为必填项'
                        },
                        {
                            type: 'exactLength[12]',
                            prompt: '备案号输入长度必须为12'
                        }
                    </#if>
                    ]
                },
                contract_no: {
                    identifier: 'contract_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '合同协议号必须填写'
                        }, {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]
                },
                transport_na: {
                    identifier: 'transport_na',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[34]',
                            prompt: '运输工具名称允许最大长度34'
                        }
                    ]
                },
                voyage_no: {
                    identifier: 'voyage_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[32]',
                            prompt: '航次号允许最大长度32'
                        }
                    ]
                },
                bl_no: {
                    identifier: 'bl_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[32]',
                            prompt: '提运单号允许最大长度32'
                        }
                    ]
                },
                license_no: {
                    identifier: 'license_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^(.){2}\-(.){2}\-(.){1,}/]',
                            prompt: '许可证号格式要求XX-XX-XXXX...'
                        },
                        {
                            type: 'maxLength[20]',
                            prompt: '许可证号允许最大长度20'
                        }

                    ]
                },
                freight2: {
                    identifier: 'freight2',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '运费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '运费值格式错误，不能为负数且保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '运费值允许最大值999999999'
                        }

                    ]
                },
                premium2: {
                    identifier: 'premium2',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '保费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '保费值格式错误，不能为负数且保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '保费值允许最大值999999999'
                        }
                    ]
                },
                otherfee2: {
                    identifier: 'otherfee2',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '杂费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '杂费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '杂费值允许最大值999999999'
                        }
                    ]
                },
                remark: {
                    identifier: 'remark',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '最大长度255'
                        }
                    ]
                },
                buyer: {
                    identifier: 'buyer',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '买方为必填项'
                        }
                    ]
                },
                agent_for_com_id: {
                    identifier: 'agent_for_com_id',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '请选择列表中的公司'
                        }
                    ]
                }
            },
            inline: true,
            on: 'blur'
        },
        goodsFormRule: {
            fields: {
                index_num: {
                    identifier: 'index_num',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品序号为必填项'
                        },
                        {
                            type: 'number',
                            prompt: '商品序号格式错误'
                        }
                    ]
                },
                /*processing_fee: {
                    identifier: "processing_fee",
                    rules: [
                    <#if d.declarationType__>
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}?$/]',
                            prompt: '工缴费格式错误'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '工缴费允许最大值999999999'
                        }
                    </#if>
                    ]
                },*/
                record_id: {
                    identifier: 'record_id',
                    rules: [
                    <#if d.declarationType__>
                        <#if d.isProcessTrade__>
                            {
                                type: 'empty',
                                prompt: '手册备案序号为必填项'

                            },
                            {
                                type: 'maxValue[999999999]',
                                prompt: '手册备案序号允许最大值999999999'
                            }
                        </#if>
                    </#if>
                    ]
                },
                code_t: {
                    identifier: 'code_t',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品编号为必填项'

                        }
                    ]
                },
                contractNumber: {
                    identifier: 'contractNumber',
                    rules: [
                    <#if d.isProcessTrade__>
                        <#if !d.declarationType__>
                            {
                                type: 'empty',
                                prompt: '合同商品项目序号为必填项'
                            },
                            {
                                type: 'maxValue[999999999]',
                                prompt: '合同商品项目序号允许最大值999999999'
                            }
                        </#if>
                    </#if>
                    ]
                },
                name: {
                    identifier: 'name',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品名称为必填项'
                        },
                        {
                            type:'maxBytes[50]',
                            prompt: '商品名称允许最大字节长度50'
                        }
                    ]
                },
                goods_mode: {
                    identifier: 'goods_mode',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '规格型号允许最大长度255'
                        }
                    ]
                },
                count: {
                    identifier: 'count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '计价数量为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '计价数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '计价数量允许最大值999999999'
                        }
                    ]
                },
                unitCode: {
                    identifier: 'unitCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '计价单位为必填项'
                        }
                    ]
                },
                total_price: {
                    identifier: 'total_price',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '总价为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,2})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,2})?$/]',
                            prompt: '总价格式错误，保留1-2位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '总价允许最大值999999999'
                        }
                    ]
                },
                unit_price: {
                    identifier: 'unit_price',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单价为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '单价格式错误，保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '单价允许最大值999999999'
                        }
                    ]
                },
                currencyCode: {
                    identifier: 'currencyCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '币制为必填项'
                        }
                    ]
                },
                legal_count: {
                    identifier: 'legal_count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '法定数量为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '法定数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '法定数量允许最大值999999999'
                        }
                    ]
                },
                legalUnitCode: {
                    identifier: 'legalUnitCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '法定单位为必填项'
                        }
                    ]
                },
                destination_code: {
                    identifier: 'destination_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '目的国为必填项'
                        }
                    ]
                },
                origin_country_code: {
                    identifier: 'origin_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '原产国为必填项'
                        }
                    ]
                },
                levyModeCode: {
                    identifier: 'levyModeCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '征免为必填项'
                        }
                    ]
                },
                second_count: {
                    identifier: 'second_count',
                    optional: true,
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '第二数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '第二数量允许最大值999999999'
                        }
                    ]
                },
                version_no: {
                    identifier: 'version_no',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[8]',
                            prompt: '版本号允许最大长度8'
                        }
                    ]
                },
                /*processing_fee: {
                identifier: 'processing_fee',
                rules: [
                {
                type: 'empty'
                }
                ]
                },*/
                package_type: {
                    identifier: 'package_type',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装种类为必填项'
                        }
                    ]
                },
                goods_gross_weight: {
                    identifier: 'goods_gross_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '毛重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重允许最大值999999999'
                        }
                    ]
                },
                goods_number: {
                    identifier: 'goods_number',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装件数为必填项'
                        },
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '包装件数允许最大值999999999'
                        }
                    ]
                },
                goods_net_weight: {
                    identifier: 'goods_net_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '净重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '净重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '净重允许最大值999999999'
                        },
                        {
                            type: 'lessThan[goods_gross_weight]',
                            prompt: '净重要小于等于毛重'
                        }
                    ]
                },
                packinglist_remark: {
                    identifier: 'packinglist_remark',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '装箱单备注内容允许最大长度255'
                        }
                    ]
                },
                goods_no: {
                    identifier: 'goods_no',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[30]',
                            prompt: '货号允许最大长度30'
                        }
                    ]
                }
            },
            inline: true,
            on: 'blur'
        },
        allFormFormatRule: {
            fields: {
                record_id: {
                    identifier: 'record_id',
                    rules: [
                    <#if d.isProcessTrade__>
                        {
                            type: 'empty',
                            prompt: '备案号为必填项'
                        },
                        {
                            type: 'exactLength[12]',
                            prompt: '备案号输入长度必须为12'
                        }
                    </#if>
                    ]
                },
                contract_no: {
                    /*identifier: 'contract_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]*/
                    identifier: 'contract_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '合同协议号必须填写'
                        }, {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]
                },
                transport_na: {
                    identifier: 'transport_na',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[34]',
                            prompt: '运输工具名称允许最大长度34'
                        }
                    ]
                },
                voyage_no: {
                    identifier: 'voyage_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[32]',
                            prompt: '航次号允许最大长度32'
                        }
                    ]
                },
                bl_no: {
                    identifier: 'bl_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[32]',
                            prompt: '提运单号允许最大长度32'
                        }
                    ]
                },
                license_no: {
                    identifier: 'license_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^(.){2}\-(.){2}\-(.){1,}/]',
                            prompt: '许可证号格式要求XX-XX-XXXX...'
                        },
                        {
                            type: 'maxLength[20]',
                            prompt: '许可证号最大长度20'
                        }
                    ]
                },
                goods_count: {
                    identifier: 'goods_count',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '件数格式错误，允许最大值999999999'
                        }
                    ]
                },
                freight2: {
                    identifier: 'freight2',
                    /*optional: 'true',*/
                    rules: [
                        {
                            type: 'empty',
                            prompt: '运费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '运费值格式错误，不能为负数且保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '运费值允许最大值999999999'
                        }
                    ]
                },
                gross_weight: {
                    identifier: 'gross_weight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重允许最大值999999999'
                        }
                    ]
                },
                net_weight: {
                    identifier: 'net_weight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '净重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '净重允许最大值999999999'
                        },
                        {
                            type: 'lessThan[gross_weight]',
                            prompt: '请输入小于等于毛重'
                        },
                        {
                            type: 'equal[total-net-weight]',
                            prompt: '总净重要等于净重总汇'
                        }
                    ]
                },
                premium2: {
                    identifier: 'premium2',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '保费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '保费值格式错误，不能为负数且保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '保费值允许最大值999999999'
                        }
                    ]
                },
                otherfee2: {
                    identifier: 'otherfee2',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '杂费值为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '杂费值格式错误，不能为负数且保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '杂费值允许最大值999999999'
                        }
                    ]
                },
                remark: {
                    identifier: 'remark',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '备注允许最大长度255'
                        }
                    ]
                }
            },
            inline: true
        },
        topFormRule: {
            fields: {
                id: {
                    identifier: 'supCompany.id',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '报关行为必填项'
                        }
                    ]
                },
                export_port_code: {
                    identifier: 'export_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '出口口岸为必填项'
                        }
                    ]
                },

                declaration_port_code: {
                    identifier: 'declaration_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '申报口岸为必填项'
                        }
                    ]
                },
                direct_transit_code: {
                    identifier: 'direct_transit_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '直航转关为必填项'
                        }
                    ]
                },
                agent_for_com_id: {
                    identifier: 'agent_for_com_id',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '请选择列表中的公司'
                        }
                    ]
                }
            },
            inline: true,
            on: 'blur'
        },
        otherFormRule: {
            fields: {
                special_relationship_confirm: {
                    identifier: 'special_relationship_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '特殊关系确认为必填项'
                        }
                    ]
                },
                price_impact_confirm: {
                    identifier: 'price_impact_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '价格影响确认为必填项'
                        }
                    ]
                },
                payment_royaltils_confirm: {
                    identifier: 'payment_royaltils_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '支付特许权使用费确认为必填项'
                        }
                    ]
                }
            },
            inline: true
        },
        soFormRule: {
            fields: {
                so: {
                    identifier: 'so',
                    rules: [
                        {
                            type: 'empty',
                            prompt: 'so号为必填项'
                        }
                    ]
                }
            },
            inline: true
        },
        declaContainersFormRule: {
            fields: {
                containerNo: {
                    identifier: 'containerNo',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '集装箱号为必填项'
                        },
                        {
                            type: 'regExp[/^[A-Z]{4}[0-9]{7}$/]',
                            prompt: '以四位大写字符开头后加7个数字'
                        }
                    ]
                },
                containerStandard: {
                    identifier: 'containerStandard',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '集装规格为必填项'
                        }
                    ]
                },
                containerWeight: {
                    identifier: 'containerWeight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '自重允许最大值999999999'
                        }
                    ]
                }

            },
            inline: true,
            on: 'blur'
        },
        suiFuDansFormRules: {
            fields: {
                suifudan_co: {
                    identifier: 'suifudan_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单证代码为必填项'
                        }
                    ]
                },
                suifudan_no: {
                    identifier: 'suifudan_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单证编号为必填项'
                        },
                        {
                            type: 'maxLength[32]',
                            prompt: '单证编号最大长度32'
                        }
                    ]
                }
            },
            inline: true,
            on: 'blur'
        },
        extendExportDeclarationFormRule: {
            fields: {
                invoice_no: {
                    identifier: 'invoice_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '发票号不能为空'
                        }
                    ]
                },
                contract_no: {
                    identifier: 'contract_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '合同协议号不能为空'
                        },
                        {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]
                },
                goods_addr_code: {
                    identifier: 'goods_addr_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '境内目的地/境内货源地不能为空'
                        }
                    ]
                }
            }
        },
        extendGeneralGoodsFormRule: {
            fields: {
                goods_mode: {
                    identifier: 'goods_mode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '要素为必填项'
                        }
                    ]
                }
            }
        }
    };
    var showError;
    var layerIndex;
    /**
     * 说明从什么页面进入此页面，目前只在客户驳回列表中使用
     */
    var prev_page = "${RequestParameters['prev_page']!}";
    var needAddProcessFee = function () {
        var processFreeRule = {
            identifier: 'processing_fee',
            rules: [
                {
                    type: 'empty',
                    prompt: '工缴费为必填项'
                },
                {
                    type: 'regExp[/^[1-9][0-9]{0,8}?$/]',
                    prompt: '工缴费格式错误'
                },
                {
                    type: 'maxValue[999999999]',
                    prompt: '工缴费允许最大值999999999'
                }
            ]
        };
        if ($.fn.order.isExport) {
            if ($.fn.order.isProcessTrade) {
                if ($("#processing_fee").parent().css("display") == "block") {
                    validationRules.goodsFormRule.fields['processing_fee'] = processFreeRule;
                } else {
                    if (validationRules.goodsFormRule.fields['processing_fee']) {
                        delete validationRules.goodsFormRule.fields['processing_fee'];
                    }
                }
            }
        }
    };
    $(document).ready(function () {
                validationRules.topFormRule.on = 'blur';
                $(".ui.topform").form(validationRules.topFormRule);
                /*validationRules.declarationFormRule.on = 'blur';*/
                $(".ui.allform").form(validationRules.declarationFormRule);
                $(".ui.goodsForm").form(validationRules.goodsFormRule);
                $(".ui#declaContainers").form(validationRules['declaContainersFormRule']);
                $(".ui#suiFuDans").form(validationRules['suiFuDansFormRules']);
                _POLICYWARN_._init();
                var $form = $("#declarationForm");
                var consistentWeight = true;
                /*抽取暂存按钮提交公用部分方法，由于新添加了对柜重的提醒*/
                function saveBtnCommon(obj) {
                    $(".ui.topform").form(validationRules.topFormRule);
                    if ($(".ui.topform").form("is valid") && consistentWeight) {
                        $form.unbind('submit');
                        obj.addDisabledClass();
                        $form.submit(function () {
                            $(this).append($("input").filter(function () {
                                var name = $(this).attr("name");
                                return !(name == undefined || name == ""
                                        || /^0.+/.test(name));
                            }).clone());
                            $(this).ajaxSubmit(
                                    {
                                        type: 'post', // 提交方式 get/post
                                        url: '<@spring.url "/business/agent/order/save" />', // 需要提交的 url
                                        /*beforeSubmit: beforeSubmitValidate,*/
                                        success: function (data) { // data 保存提交后返回的数据，一般为 json 数据
                                            // 此处可对 data 作相关处理
                                            console.log(data);
                                            var tipMsg;
                                            if (data.result == true) {
                                                tipMsg = data.msg;
                                                layer.alert(tipMsg, function (index) {
                                                    layer.close(index);
                                                          <#if d.isInsertPage__>
                                                              location.href =
                                                                      "<@spring.url "/business/agent/order/update?id=" />"
                                                                      + data.data;
                                                          <#else>
                                                              var sliceLen = $.fn.order.isExport
                                                                      ? 4 : 2;
                                                              var $iframes = $("iframe").slice(0,
                                                                      sliceLen);
                                                              $.each($iframes, function (i, n) {
                                                                  n.contentWindow.location.reload();
                                                              });
                                                          </#if>
                                                    /*如果页面来自excel导入报关单*/
                                                    if (location.pathname
                                                            == '/business/agent/order/update'
                                                            && location.search == '?id=') {
                                                        location.replace('update?id='
                                                                + data.data);
                                                    }
                                                });
                                            } else {
                                                if (data.data) {
                                                    tipMsg =
                                                            data.msg + "<br/>错误原因：" + data.data;
                                                } else {
                                                    tipMsg = data.msg;
                                                }
                                                layer.alert(tipMsg);
                                            }
                                            //$(this).resetForm(); // 提交后重置表单
                                            $("#saveBtn").removeDisabledClass();
                                        }
                                    });
                            $form.empty();
                            return false;
                        });
                        $form.submit();
                    } else {
                        return false;
                    }
                }

                /*暂存按钮*/
                $("#saveBtn").click(function () {
                    var iaAgentVal=$("input[name=isAgent]").val();
                    console.log(iaAgentVal);
                            delete validationRules.topFormRule.on;
                            $(".ui.topform").form(validationRules.topFormRule);
                            if ($(".ui.topform").form("is valid")) {
                                $form.unbind('submit');
                                $(this).addDisabledClass();
                                $form.submit(function () {
                                    $(this).append($("input").filter(function () {
                                        var name = $(this).attr("name");
                                        return !(name == undefined || name
                                                == ""
                                                || /^0.+/.test(name));
                                    }).clone());
                                    $(this).ajaxSubmit(
                                            {
                                                type: 'post', // 提交方式 get/post
                                                url: '<@spring.url "/business/agent/order/save" />', // 需要提交的 url
                                                /*beforeSubmit: beforeSubmitValidate,*/
                                                success: function (data) { // data 保存提交后返回的数据，一般为 json 数据
                                                    // 此处可对 data 作相关处理
                                                    console.log(data);
                                                    var tipMsg;
                                                    if (data.result == true) {
                                                        tipMsg = data.msg;
                                                        layer.alert(tipMsg,
                                                                function (index) {
                                                                    layer.close(index);
                                                                                          <#if d.isInsertPage__ || d.isReject__>
                                                                                              location.href =
                                                                                                      "<@spring.url "/business/agent/order/update?id=" />"
                                                                                                      + data.data;
                                                                                          <#else>
                                                                                              var sliceLen = $.fn.order.isExport
                                                                                                      ? 4
                                                                                                      : 2;
                                                                                              var $iframes = $("iframe").slice(0,
                                                                                                      sliceLen);
                                                                                              $.each($iframes,
                                                                                                      function (i,
                                                                                                                n) {
                                                                                                          n.contentWindow.location.reload();
                                                                                                      });
                                                                                          </#if>
                                                                    /*如果页面来自excel导入报关单*/
                                                                    if (location.pathname
                                                                            == '/business/agent/order/update'
                                                                            && location.search
                                                                            == '?id=') {
                                                                        location.replace('/business/agent/order/update?id='
                                                                                + data.data);
                                                                    }
                                                                });
                                                    } else {
                                                        if (data.data) {
                                                            tipMsg =
                                                                    data.msg
                                                                    + "<br/>错误原因："
                                                                    + data.data;
                                                        } else {
                                                            tipMsg = data.msg;
                                                        }
                                                        layer.alert(tipMsg);
                                                    }
                                                    //$(this).resetForm(); // 提交后重置表单
                                                    $("#saveBtn").removeDisabledClass();
                                                    validationRules.topFormRule.on =
                                                            'blur';
                                                }
                                            });
                                    $form.empty();
                                    return false;
                                });
                                $form.submit();
                            } else {
                                validationRules.topFormRule.on = 'blur';
                                $(".ui.topform").form(validationRules.topFormRule);
                                return false;
                            }
                        }
                );

                $("#returnBtn").click(function () {
                    var id = '${declaration.id}';
                    if (id) {
                        $.ajax({
                            url: '/datalock/onUnlock.do?opaId=VDBS&bidId=${declaration.id}',
                            async: false
                        });
                    }
                    history.go(-1);
                });
//新增按钮
                $("#newBtn").click(function () {
                          <#if d.declarationType__>
                              location.href =
                                      "<@spring.url "/business/agent/order/out/"+((declaration.tradeType=='0')?string('general','process')) />?isCCI=<#if (declaration.isTongguanYth)?length==0>0<#else>${declaration.isTongguanYth}</#if>";
                          <#else>
                              location.href =
                                      "<@spring.url "/business/agent/order/in/"+((declaration.tradeType=='0')?string('general',((declaration.tradeType=='1')?string('process','special')))) />?isCCI=<#if (declaration.isTongguanYth)?length==0>0<#else>${declaration.isTongguanYth}</#if>";
                          </#if>
                });
                showError = function (errores) {
                    if (errores.length == 0) {
                        return;
                    }
                    var $error = $("#errorMsg");
                    var errorStr = "";
                    $.each(errores, function (i, n) {
                        errorStr += " <li class='errorList' > " + n + " </li> ";
                    });
                    $error.html(errorStr);
                    $error.show().delay(3000).hide(0, function () {
                        $(this).empty();
                    });
                };
//验证前还需要一些准备
                if ($.fn.order.isExport) {
                    var __fields = $.extend({},
                            validationRules.declarationFormRule.fields,
                            validationRules.extendExportDeclarationFormRule.fields);
                    validationRules.declarationFormRule.fields = __fields;
                    if ($.fn.order.isGeneralTrade) {
                        var _generalTradeFields = $.extend({},
                                validationRules.goodsFormRule.fields,
                                validationRules.extendGeneralGoodsFormRule.fields);
                        validationRules.goodsFormRule.fields = _generalTradeFields;
                    }
                    needAddProcessFee();
                }
//检测商品信息必填项是否都填写完整
                var goodsInfoRequired = function () {
                    var $goodsForm = $("#commodities");
                    var $goodsTable = $goodsForm.nextAll("table");
                    var $goodsSaveBtn = $("#goodsSave");
                    $goodsTable.find(".primary.basic.button").each(function (i, n) {
                                $(n).click();
                                isShowTip = false;
                                $goodsSaveBtn.click();
                                if (!globalGoodsBool) {
                                    return false;
                                }

                            }
                    );
                    if (globalGoodsBool && checkTgyth()) {
                        return true;
                    }

                }

//提交
                beforeSubmitValidate = function () {
                    if (goodsInfoRequired()) {
                        /*if (parseInt($("input[name=gross_weight]").val()) / 1000 > 28
                                                                                   * $("table[name=containerTable]").find("tbody tr").length) {

                            addShowErrors("超出限载重量!");
                        }*/
                        delete validationRules['declarationFormRule'].on;
                        $('.ui.allform').form.settings.on = 'submit';
                        delete validationRules['topFormRule'].on;
                        $(".ui.topform").form.settings.on = 'submit';
                        $('.ui.allform').form(validationRules.declarationFormRule);
                        $(".ui.topform").form(validationRules.topFormRule);
                        $(".ui.otherForm").form(validationRules.otherFormRule);
                        var topSubmitValid = $(".ui.topform").form("is valid");
                        var allSubmitValid = $('.ui.allform').form('is valid');
                        var otherSubmitValid = $('.ui.otherForm').form('is valid');
                        var goodsFormLen = $("#commodities").nextAll("table").find("tbody tr").length;
                        var declaContainersLen = $("#declaContainers").nextAll("table")
                                .find("tbody tr").length;
                        var is_wood_packaging = $("input[name='is_wood_packaging']:checked").val();
                        var is_wood_packaging_boolean = false;
                        if (is_wood_packaging) {
                            is_wood_packaging_boolean = true;
                        }
                        var totalPriceBool = true;
                        var $goodsTableTarget = $("#goodsTable").find("tfoot tr th").find(".ui.basic");
                        var totalPrice = ($goodsTableTarget.length == 1)
                                ? $goodsTableTarget.find(".detail").text()
                                : $goodsTableTarget.eq(3).find(".detail").text();
                        if (parseFloat(totalPrice) > 999999999) {
                            totalPriceBool = false;
                        }
                        var soSubmitValid = true;
                        if ($("#SO_DIV").attr("style") != "display: none;") {
                            $(".ui.soForm").form(validationRules.soFormRule);
                            soSubmitValid = $('.ui.soForm').form('is valid');
                        }

                        if (topSubmitValid && allSubmitValid && otherSubmitValid
                                && soSubmitValid
                                && goodsFormLen && is_wood_packaging_boolean && totalPriceBool
                                && (/\d+/.test($("#supCompany_quotPrice").text()))) {
                            if (declaContainersLen != 0) {
                                var cabinetNo = [];
                                var json = {};
                                $.each($("#declaContainers").nextAll("table").find("tbody tr"),
                                        function (i, n) {
                                            var cabinetNoVal = $(n).find("td").eq(0).text();
                                            cabinetNo.push(cabinetNoVal);
                                        });
                                for (var i = 0; i < cabinetNo.length; i++) {
                                    if (!json[cabinetNo[i]]) {
                                        json[cabinetNo[i]] = 1;
                                    } else {
                                        if ($(".errorMsgContainer").css("display")
                                                == "block") {
                                            $(".modal-body").append('<li class="errorList">重复获取柜号! </li>');
                                        } else {
                                            $(".errorMsgContainer").show();
                                            $(".error.message").show();
                                            $(".modal-body").append('<li class="errorList">重复获取柜号! </li>');
                                        }
                                        break;
                                    }
                                }
                                return true;
                            }
                            $(".compareTip").removeClass("compareTip");
                        } else {
                            if (!(topSubmitValid && allSubmitValid && otherSubmitValid
                                            && is_wood_packaging_boolean && soSubmitValid
                                            && totalPriceBool
                                            && goodsFormLen
                                            && (/\d+/.test($("#supCompany_quotPrice").text())))) {
                                if (goodsFormLen == 0) {
                                    addShowErrors("没有商品信息!");
                                }
                                if (!totalPriceBool) {
                                    addShowErrors("总价总汇允许的最大值为999999999!");
                                }
                                if (!is_wood_packaging_boolean) {
                                    addShowErrors("没有选择是否木质包装信息!");
                                }
                                if (!(/\d+/.test($("#supCompany_quotPrice").text()))) {
                                    addShowErrors("该报关行没有报价不能提交!");
                                }
                                layer.close(layerIndex);
                                $("#submitBtn").removeDisabledClass();
                                validationRules['declarationFormRule'].on = 'blur';
                                $('.ui.allform').form(validationRules.declarationFormRule);
                                return false;
                            }
                        }
                    } else {
                        $("#submitBtn").removeDisabledClass();
                        layer.close(layerIndex);
                        return false;
                    }

                }
                ;

                var $form = $("#declarationForm");
                $("#submitBtn").click(function () {
                    $form.unbind('submit');
                    $(this).addDisabledClass();
                    $form.submit(function () {
                        var __url = '<@spring.url "/business/agent/order/submit" />';
                        if (prev_page && prev_page == 'customerReject') {
                            __url = '<@spring.url "/business/agent/order/customerRejectSubmit" />';
                        }
                        $(this).append($("input").filter(function () {
                            var name = $(this).attr("name");
                            return !(name == undefined || name == ""
                                    || /^0.+/.test(name));
                        }).clone());
                        $(this).ajaxSubmit(
                                {
                                    type: 'post', // 提交方式 get/post
                                    url: __url, // 需要提交的 url
                                    beforeSubmit: beforeSubmitValidate,
                                    success: function (data) { // data 保存提交后返回的数据，一般为 json 数据
// 此处可对 data 作相关处理
                                        console.log(data);
                                        var tipMsg;
                                        if (data.result == true) {
                                            /*做了驳回以后有让去直接去更新左侧的数据 不去后台取  直接减一*/
                                            if (prev_page == 'customerReject') {
                                                try {
                                                    window.top.rejectCount__ =
                                                            (window.top.rejectCount__ - 1);
                                                    window.top.loadRejectCount();
                                                } catch (exe) {
                                                }
                                            }
                                            tipMsg = data.msg;
                                            layer.alert(tipMsg, function (index) {
                                                layer.close(index);
                                                location.href =
                                                        "<@spring.url "/order/payPage?id="/>"
                                                        + data.data;
                                            });
                                        } else {
                                            if (data.data) {
                                                tipMsg =
                                                        data.msg + "<br/>错误原因：" + data.data;
                                            } else {
                                                tipMsg = data.msg;
                                            }
                                            layer.alert(tipMsg);
                                        }
                                        $("#submitBtn").removeDisabledClass();
                                    }
                                });
                        $form.empty();
                        return false;
                    });
                    layer.close(layerIndex);
                    $("div .required").next("div.field").not(".disabled").css('background-color',
                            '#FFFFCC');
                    $("div .required").next("div.field").not(".disabled").find("input[type='text']")
                            .css('background-color',
                                    '#FFFFCC');
                    $("#goodsTable").find("tbody").css('background-color', '#FFFFCC');
                    if ($("#declaContainers").nextAll("table").find("tbody tr").length
                            == 0) {
                        layerIndex = layer.confirm('系统检测到您没有录入柜号，请确认是否为散货？', {
                            btn: ['是', '否']
                        }, function () {
                            $(".layui-layer-btn0").addClass("layerYesDisabled");
                            layerIndex =
                                    layer.confirm(
                                            "以下内容客户录入差错率较高，产生影响较大，请重新核对！请重新核查以下内容：商品品名，商品规格，成交方式，币制，收发货人，数量",
                                            {
                                                btn: ['是', '否']
                                            }, function () {
                                                $(".layui-layer-btn0").addClass("layerYesDisabled");
                                                $form.submit();
                                            }, function () {
                                                $("#submitBtn").removeDisabledClass();
                                            });
                        }, function () {
                            doShowForm(true, $("#containersAdd"), $("#containersSave"),
                                    $("#containersCancle"),
                                    $("#declaContainers"));
                            $("#containerNo").focus();
                            $("#submitBtn").removeDisabledClass();
                        });
                    } else {
                        if (parseInt($("input[name=gross_weight]").val()) / 1000 > 28
                                * $(
                                        "table[name=containerTable]").find("tbody tr").length) {

                            /*addShowErrors("超出限载重量!");*/
                            var weightTipIndex = layer.confirm('超出限载重量!是否重新修改毛重信息？', {
                                btn: ['是', '否'] //按钮
                            }, function () {
                                layer.close(weightTipIndex);
                                $("#submitBtn").removeDisabledClass();
                                $("input[name=gross_weight]").focus();
                            }, function () {
                                layer.close(weightTipIndex);
                                $("#submitBtn").removeDisabledClass();
                                layerIndex =
                                        layer.confirm(
                                                "以下内容客户录入差错率较高，产生影响较大，请重新核对！请重新核查以下内容：商品品名，商品规格，成交方式，币制，收发货人，数量",
                                                {
                                                    btn: ['是', '否']
                                                }, function () {
                                                    $(".layui-layer-btn0").addClass("layerYesDisabled");
                                                    $form.submit();
                                                }, function () {
                                                    $("#submitBtn").removeDisabledClass();
                                                });
                            });
                        } else {
                            layerIndex =
                                    layer.confirm(
                                            "以下内容客户录入差错率较高，产生影响较大，请重新核对！请重新核查以下内容：商品品名，商品规格，成交方式，币制，收发货人，数量",
                                            {
                                                btn: ['是', '否']
                                            }, function () {
                                                $(".layui-layer-btn0").addClass("layerYesDisabled");
                                                $form.submit();
                                            }, function () {
                                                $("#submitBtn").removeDisabledClass();
                                            });
                        }

                    }

                });

//使用模板
                $("#useTemplateBtn").click(function () {
                    loadBizFromHistoryOperation();
                });
                function generateUUID() {
                    var d = new Date().getTime();
                    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                            function (c) {
                                var r = (d
                                        + Math.random()
                                        * 16)
                                        % 16
                                        | 0;
                                d =
                                        Math.floor(d
                                                / 16);
                                return (c
                                == 'x'
                                        ? r
                                        : (r
                                                & 0x3
                                                | 0x8)).toString(
                                        16);
                            });
                    return uuid;
                }
                ;
//查看编辑报关单资料
                var bill_no = '${declaration.id}';
                $("#uploadDeclarationAttachmentBtn").click(function () {
                    if (bill_no == '') {
                        bill_no = generateUUID();
                        $("input[name='tempAttachmentBillNo']").val(bill_no);
                    }
                    layer.open({
                        type: 2,
                        offset: ['5%', '12%'],
                        content: '/business/uploadMain?type=declaration#'
                        + bill_no,
                        area: ['815px', '620px']
                    });
                });
//另存为模板
                $("#prepareSveAsModel").click(function () {
                    var businessId = '${declaration.businessId}';
                    var url = window.location.href;
                    var isAgent=$("input[name='isAgent']").val();
                    if (url.concat("general")) {
                        prepareSveAsModel("F", businessId,isAgent);
                    } else {
                        prepareSveAsModel("T", businessId,isAgent);
                    }
                });
            }
    )
    ;
    /**
     *从历史业务数据载入模版，页面导航
     *bizType = [all, booking, trail, declaration]
     */
    function loadBizFromHistory() {
//        layer.confirm("检测到当前页面有未保存的业务数据，是否继续操作，点击确认将覆盖当前数据?", function () {
//            loadBizFromHistoryOperation(bizType);
//        }, function () {
//            return;
//        });
        loadBizFromHistoryOperation();
    }

    /**
     *从历史业务数据载入模版，真实操作
     *bizType = [all, booking, trail, declaration]
     */
    function loadBizFromHistoryOperation() {
        layer.open({
            type: 2,
            offset: ['5%', '12%'],
            content: '/business/model-main?type=' + $("input[name='tradeType']").val()
            + '&dType=' + $("input[name='declaration_type']").val()
            + '&isTongguanYth='
            + $('#isTongguanYth').val() + "&isAgent="+$("input[name='isAgent']").val(),
            area: ['815px', '620px']
        });
    }

    /**
     * 另存为模板
     */
    function prepareSveAsModel(isRecordInfo, businessId,isAgent) {
        layer.open({
            type: 2,
            content: "/business/prepareSveAsModel?isRecordInfo=" + isRecordInfo
            + "&businessId=" + businessId +"&isAgent="+ isAgent ,
            area: ['600px', '300px']
        });
    }

    /**
     * 保存为模板，现由子页面进行调用
     * @param modelName 模板名称
     * @param modelType 模板类型
     */
    function saveAsModel(modelName, modelType, isRecordInfo, businessId) {
        var $inputs = $("input").filter(function () {
            var name = $(this).attr("name");
            return !(name == undefined || name == "" || /^0.+/.test(name));
        });
        var data = {};
        $.each($inputs, function (i, n) {
            data[n.name] = n.value;
        });
        if (data.length == 0) {
            alert("保存失败，请刷新页面后重试");
            return;
        }
        data.modelName = modelName;
        data.modelType = modelType;
        data.isRecordInfo = isRecordInfo;
        data.businessId = businessId;
        data.isTongguanYth = $('#isTongguanYth').val();
        layer.load(2, {shade: [0.2]});
        $.ajaxPlugin({
            url: '<@spring.url "/business/saveAsModel"/>',
            data: data,
            method: 'POST',
            dataType: 'json',
            success: function (result) {
                layer.closeAll();
                result = $.parseJSON(result);
                if (result.rs == "1") {
                    layer.alert("保存成功");
                } else if (result.rs == "-1") {
                    layer.alert("校验错误，错误信息[" + result.code + "]");
                } else {
                    layer.alert("发生了错误，CODE[" + result.code + "]");
                }
            },
            error: function () {
                layer.closeAll();
                layer.alert("发生了错误，CODE[001]");
            }
        });
    }

</script>
